package com.leetcode.matrix;

public class SearchMatrix {
    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix.length;
        int m = matrix[0].length;
        boolean res = false;
        int ind = -1;
        for (int i = 0; i < n; i++) {
           if (target < matrix[i][0]) {
               break;
           }
           if (target <= matrix[i][m - 1]) {
               ind = i;
               break;
           }
        }
        if (ind == -1) {
            return false;
        }
        int left = 0;
        int right = m - 1;
        while(left <= right) {
            int mid = left + (right - left) / 2;
            if (matrix[ind][mid] == target) {
                return true;
            } else if (matrix[ind][mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return false;
    }
}
